<template>
  <div class="view-fill">
    <div
      v-if="
        !detailInfo.visible &&
        !receiptModifyInfo.visible &&
        !detailOtherStoreOrderInfo.visible &&
        !surgeryDetailInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canRetract" @click="retract">撤回</el-button>
          <el-button v-if="canRatify" @click="ratify">批准</el-button>
          <el-button v-if="canReject" @click="reject">驳回</el-button>
          <el-button v-if="canReset" @click="reset">重置</el-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button v-if="canPrint" @click="print">打印</el-button> -->
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!--:image-field="infoList.imageField"查看图片-->
            <basic-information
              :info="infoList"
              :label-width="infoList.labelWidth"
            ></basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>附件信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="receiptList">
              <template v-slot:basic-billAnnexPathList>
                <span v-if="receiptList.data.billFilePath">
                  <ele-gallery
                    :lazy="true"
                    :size="150"
                    :source="receiptList.data.billAnnexPathList"
                    title="发票附件"
                  ></ele-gallery>
                </span>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="'关联信息'"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <page-table
                class="table-scroll-hidden"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
                <template v-slot:col-orderNo="scope">
                  <span
                    v-if="
                      $permission('receiving:detail') &&
                      scope.row.receivingType === 'receiving_order'
                    "
                    class="slip-edit"
                    @click="showDetail(scope.row)"
                    >{{ scope.row.orderNo || '-' }}</span
                  >
                  <span
                    v-else-if="scope.row.receivingType === 'other_store'"
                    class="slip-edit"
                    @click="showDetail(scope.row)"
                    >{{ scope.row.orderNo || '-' }}</span
                  >
                  <span
                    v-else-if="
                      $permission('surgeryAndTableReceipt:detail') &&
                      scope.row.receivingType === 'with_table_receiving_order'
                    "
                    class="slip-edit"
                    @click="showDetail(scope.row)"
                    >{{ scope.row.orderNo || '-' }}</span
                  >
                  <span
                    v-else-if="
                      scope.row.receivingType === 'with_table_receiving_order'
                    "
                    >{{ scope.row.orderNo || '-' }}</span
                  >
                </template>
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 明细 -->
    <receipt-modify
      v-if="receiptModifyInfo.visible"
      :id="receiptModifyInfo.id"
      v-model:visible="receiptModifyInfo.visible"
      :title="receiptModifyInfo.title"
    />
    <other-store-order-detail
      v-if="detailOtherStoreOrderInfo.visible"
      :id="detailOtherStoreOrderInfo.id"
      v-model:visible="detailOtherStoreOrderInfo.visible"
    />
    <ReceivingOrderDetail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
    />
    <SurgeryAndTableReceiptDetails
      v-if="surgeryDetailInfo.visible"
      :id="surgeryDetailInfo.id"
      v-model:visible="surgeryDetailInfo.visible"
    />
  </div>
</template>

<script setup name="receiptDetails">
import BasicInformation from '@/components/BasicInformation/index'
import {
  recipetById,
  recipetReceivingOrderList,
  submitBillRegistration, //提交
  retractBillRegistration, //撤回
  ratifyBillRegistration, //批准
  rejectBillRegistration, //驳回
  resetBillRegistration, //重置
  getReceiptPrint, //打印
} from '@/api/receipt.js'
import PageTable from '@/components/PageTable/index'
import EleGallery from '@/components/UploadImg/eleGallery'
import receiptModify from './modify'
import OtherStoreOrderDetail from '@/views/stock/otherStore/detail'
import { fatchTemplateByCode } from '@/api/base'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const SurgeryAndTableReceiptDetails = defineAsyncComponent(() =>
  import('@/views/stock/surgeryAndTableReceipt/detail')
)
const ReceivingOrderDetail = defineAsyncComponent(() =>
  import('@/views/stock/receiving/detail')
)

const props = defineProps({
  visible: {
    type: Boolean,
  },
  id: {
    type: [String, Number],
  },
})

const title = '收票登记详情'
const infoList = reactive({
  data: {},
  fieldList: [
    { label: '付款机构', value: 'payOrgName', type: 'text' },
    { label: '收款机构', value: 'collectOrgName', type: 'text' },
    { label: '发票号码', value: 'billNumber', type: 'text' },
    {
      label: '票面金额(元)',
      value: 'billAmount',
      type: 'text',
      formatter: proxy.$fn.TripartiteMethod,
    },
    { label: '经办人', value: 'operator', type: 'text' },
    { label: '收票日期', value: 'receiveDate', type: 'text' },
    { label: '发票张数', value: 'billCount', type: 'text' },
    { label: '发票日期', value: 'billDate', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
  labelWidth: '135px',
})
const receiptList = reactive({
  data: {},
  fieldList: [{ label: '发票附件', value: 'billAnnexPathList', type: 'slot' }],
})
const fullInfo = reactive({
  btnList: [
    // { label: "打印", event: print, show: proxy.$permission("receipt:print")  }
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {},
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'billAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    { label: '单号', value: 'orderNo', type: 'slot' },
    { label: '供应商', value: 'supplierName' },
    { label: '入库日期', value: 'storeTime' },
    {
      label: '金额',
      value: 'billAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
const receiptModifyInfo = reactive({
  id: '',
  visible: false,
  title: '',
})
const detailInfo = reactive({
  visible: false,
  id: '',
})
const detailOtherStoreOrderInfo = reactive({
  visible: false,
  id: '',
})
const surgeryDetailInfo = reactive({
  visible: false,
  id: '',
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSubmit = computed(() => {
  return proxy.$permission('receipt:submit') && infoList.data.status === 1
})
const canUpdate = computed(() => {
  return proxy.$permission('receipt:update') && infoList.data.status === 1
})
const canRetract = computed(() => {
  return proxy.$permission('receipt:retract') && infoList.data.status === 2
})
const canReject = computed(() => {
  return proxy.$permission('receipt:reject') && infoList.data.status === 2
})

const canRatify = computed(() => {
  return proxy.$permission('receipt:ratify') && infoList.data.status === 2
})
const canReset = computed(() => {
  return proxy.$permission('receipt:reset') && infoList.data.status === 4
})
const canPrint = computed(() => {
  return proxy.$permission('receipt:print') && infoList.data.status === 4
})
watch(
  () => props.visible,
  (newVal) => {
    showDialog.value = newVal
  },
  {
    immediate: true,
  }
)
watch(
  () => receiptModifyInfo.visible,
  (value) => {
    if (!value && props.id) {
      getMain()
      getList()
    }
  }
)

onMounted(() => {
  if (props.id) {
    getMain()
    getList()
  }
})

function returnBack() {
  emit('returnBack', false)
}
function update() {
  //编辑
  receiptModifyInfo.id = props.id
  receiptModifyInfo.title = '修改收票登记'
  receiptModifyInfo.visible = true
}
function submit() {
  //提交
  let ids = [props.id]
  submitBillRegistration(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function ratify() {
  //批准
  let ids = [props.id]
  ratifyBillRegistration(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function retract() {
  //撤回
  let ids = [props.id]
  retractBillRegistration(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function reject() {
  //驳回
  proxy
    .$prompt('驳回理由', '收票登记', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^[\S]+/,
      inputErrorMessage: '请输入驳回理由',
    })
    .then(({ value }) => {
      const data = {
        id: props.id,
        rejectReason: value,
      }
      rejectBillRegistration(data).then((resp) => {
        if (resp && resp.success) {
          refreshDetail()
        }
      })
    })
    .catch(() => {})
}
function reset() {
  //重置
  proxy
    .$confirm('此操作将更新数据, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let ids = [props.id]
      resetBillRegistration(ids).then((resp) => {
        if (resp && resp.success) {
          refreshDetail()
        }
      })
    })
    .catch((e) => {})
}
function refreshDetail() {
  getMain()
  getList()
}
function showDetail(row) {
  if (row.receivingType === 'receiving_order') {
    detailInfo.id = row.receivingId
    detailInfo.visible = true
  } else if (row.receivingType === 'other_store') {
    detailOtherStoreOrderInfo.visible = true
    detailOtherStoreOrderInfo.id = row.receivingId
  } else if (row.receivingType === 'with_table_receiving_order') {
    surgeryDetailInfo.visible = true
    surgeryDetailInfo.id = row.receivingId
  }
}
function getMain() {
  recipetById(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
      receiptList.data = resp.data
    }
  })
}
function getList() {
  let params = { billRegistrationId: props.id }
  recipetReceivingOrderList(params).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data.map((m) => {
        m.orderNo = m.receivingOrderVO.orderNo
        m.supplierName = m.receivingOrderVO.supplierName
        m.storeTime = m.receivingOrderVO.storeTime
        m.billAmount = m.receivingOrderVO.billAmount
        m.receivingId = m.receivingOrderVO.id
        return m
      })
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
function print() {
  selectByCodeAndDept({
    tempCode: 'billRegistrationDetail',
    deptId: infoList.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: infoList.data.id,
            orderNo: infoList.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
  /*  fatchTemplateByCode({
    resourceCode: 'receipt:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp)
    }
  }) */
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.data.billCode,
      orderId: infoList.data.id,
      tempCode: 'billRegistrationDetail',
      orderType: 4,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: infoList.data.id,
      orderNo: infoList.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function getPrintData(temp) {
  let params = {
    orderIds: [props.id],
  }
  getReceiptPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
</script>
